package com.it.service.impl;

import com.it.mapper.RoleMapper;
import com.it.mapper.UserMapper;
import com.it.pojo.Role;
import com.it.pojo.RoleExample;
import com.it.pojo.User;
import com.it.service.RoleService;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zgc
 * @version: 1.0
 * @description:
 * @date: 2023/12/15 15:02
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Role findById(String id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> findAll() {
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        criteria.andRoleDelEqualTo(0);
        List<Role> list = roleMapper.selectByExample(example);
        return list;
    }

    @Override
    public int updateRoleId(String roleId,String userId) {
        User user = userMapper.selectByPrimaryKey(userId);
        user.setRoleId(roleId);
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public int deleteByRolId(String roleId) {
        Role role = new Role();
        role.setRoleId(roleId);
        role.setRoleDel(1);
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public int updateRole(Role role) {
        if (!StringUtils.isNullOrEmpty(role.getRoleId())){
            /*修改*/
            return roleMapper.updateByPrimaryKeySelective(role);
        }else{
            /*添加*/
            role.setRoleId(getPrimaryKey());
            System.out.println(role);
            return roleMapper.insertSelective(role);
        }
    }

    public String getPrimaryKey(){
        RoleExample example = new RoleExample();
        RoleExample.Criteria criteria = example.createCriteria();
        List<Role> list = roleMapper.selectByExample(example);
        return list.size()+1+"";
    }


}
